import { UniNamespace } from '@dcloudio/types';
// import { baseURL } from '@/utils/config.ts';
// 基础配置
const baseConfig: UniNamespace.RequestOptions = {
    baseURL: 'https://www.mrxc915.com/ai',
	// baseURL: 'http://121.40.122.64:8183/ai/',
	
    timeout: 999999999999999999
};

// 封装请求方法
const request = <T>(options: UniNamespace.RequestOptions): Promise<T> => {
    return new Promise((resolve, reject) => {
        // 合并基础配置和传入的配置
        const mergedOptions: UniNamespace.RequestOptions = {
           ...baseConfig,
           ...options,
            url: baseConfig.baseURL + options.url
        };
		console.log(mergedOptions)
		// 请求拦截器：添加 token 到请求头
		        const token = uni.getStorageSync('Token');
		        // console.log('获取到的 token:', token); // 打印获取到的 token，用于调试
		        if (token) {
		            mergedOptions.header = {
		               ...(mergedOptions.header || {}), // 确保 mergedOptions.header 存在
		                'X-Access-Token': `${token}`
		            };
		            // console.log('添加 token 后的请求头:', mergedOptions.header); // 打印添加 token 后的请求头
		        }
        uni.request({
           ...mergedOptions,
            success: (res) => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data as T);
                } else {
                    reject(new Error(`请求失败，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                reject(new Error(err.errMsg));
            }
        });
    });
};

// 封装 GET 请求
const get = <T>(url: string, params?: any): Promise<T> => {
    return request<T>({
        url,
        method: 'GET',
        data: params
    });
};

// 封装 POST 请求
const post = <T>(url: string, data?: any): Promise<T> => {
    return request<T>({
        url,
        method: 'POST',
        data
    });
};


// 封装 DELETE 请求
const del = <T>(url: string, params?: any): Promise<T> => {
    return request<T>({
        url,
        method: 'DELETE',
        data: params
    });
};
export { get, post,baseConfig,del };    